package com.jackstraw.jack_base.datasource.database.parten.entity.bean;

import com.jackstraw.jack_base.datasource.common.entity.enums.RWEnum;
import com.jackstraw.jack_base.datasource.database.parten.aspect.contextholder.DataBaseRWContextHolder;
import com.jackstraw.jack_base.datasource.database.parten.entity.DataBaseEntity;
import com.jackstraw.jack_base.datasource.database.parten.entity.enums.DataBaseSchemaTypeEnum;
import com.jackstraw.jack_base.datasource.database.parten.exception.BadDataBaseException;
import com.jackstraw.jack_base.util.CollectionUtil;
import com.jackstraw.jack_base.util.ObjectUtil;
import com.jackstraw.jack_base.util.RandomUtil;
import lombok.Data;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;


/**
 * 单数据源
 * <p>
 * 包含改数据源下读写数据源
 */
@Data
public class DataBaseRoutingDataSource<DBE extends DataBaseEntity<DBE>> extends AbstractRoutingDataSource {


    /**
     * 读数据源
     */
    private List<String> readDataBaseNameList;

    /**
     * 写数据源
     */
    private List<String> writeDataBaseNameList = new ArrayList<>();

    /**
     * 配置文件
     */
    private DataBasePropertiesEntity<DBE> propertiesEntity;


    @Override
    protected Object determineCurrentLookupKey() {
        if (DataBaseSchemaTypeEnum.none.equals(propertiesEntity.getDataBaseSchemaTypeEnum())) {
            return null;
        }

        RWEnum rwEnum = DataBaseRWContextHolder.get();
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(rwEnum)) {
            return null;
        }

        switch (rwEnum) {
            case write:
                //判断集合是否为空
                if (CollectionUtil.isEmpty(this.writeDataBaseNameList)) {
                    throw new BadDataBaseException("001", "写数据源为空");
                }
                return writeDataBaseNameList.get(RandomUtil.RandomUtilByHutool.randomInt(writeDataBaseNameList.size()));
            case read:
                //判断集合是否为空
                if (CollectionUtil.isEmpty(this.readDataBaseNameList)) {
                    throw new BadDataBaseException("002", "读数据源为空");
                }
                return readDataBaseNameList.get(RandomUtil.RandomUtilByHutool.randomInt(readDataBaseNameList.size()));
            case none:
                return null;
        }

        return null;
    }


    public DataSource get() {
        return determineTargetDataSource();
    }
}
